package jenry.progressbarhandler;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;

public class Gan_ProgressBarHandler extends Activity {
    /** Called when the activity is first created. */
	ProgressBar bar = null;
	Button startButton = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        bar = (ProgressBar)findViewById(R.id.bar);
        startButton = (Button)findViewById(R.id.startButton);
        startButton.setOnClickListener(new ButtonListener());
        System.out.println("OnCreate---->" + Thread.currentThread().getId());
        System.out.println("OnCreate---->" + Thread.currentThread().getName());
    }
    
    class ButtonListener implements OnClickListener{
		public void onClick(View v) {
			bar.setVisibility(View.VISIBLE);
			updateBarHandler.post(updateThread);
		}
    }
    
    Handler updateBarHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			bar.setProgress(msg.arg1);
			Bundle bundle = msg.getData();
			updateBarHandler.post(updateThread);
			System.out.println("test---->" + bundle.getString("test"));
		}
    };
    
    Runnable updateThread = new Runnable(){
    	int i=0;
		public void run() {
			System.out.println("Begin Thread" +i);
			System.out.println("Runnable---->" + Thread.currentThread().getId());
	        System.out.println("Runnable---->" + Thread.currentThread().getName());
			i = i+10;
			Message msg = updateBarHandler.obtainMessage();
			msg.arg1 = i;
			Bundle bundle = new Bundle();
			bundle.putString("test","test bundle");
			msg.setData(bundle);
			try{
				Thread.sleep(1000);
			}
			catch(InterruptedException e){
				e.printStackTrace();
			}
			if(i > 100){
				bar.setVisibility(View.GONE);
				updateBarHandler.removeCallbacks(updateThread);
				System.out.println(">>>>>>");
			}else{
				updateBarHandler.sendMessage(msg);
				System.out.println(">>>>>>");
			}
		}
	};
    
}